package com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.send;

import cn.hutool.core.util.StrUtil;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Config;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Exception;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.channel.send.S30SendChannel;
import com.cetccloud.ap.util.IdUtil;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayDataDest;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayDataMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MessageHandler
 * @Description 消息传输
 * @Author superz
 * @Date 2021/4/23 12:06
 * @Version 1.0
 **/
@Slf4j
@Component("sendMessageHandler")
public class MessageHandler {

    @Autowired
    private S30Config s30Config;

    @Autowired
    private S30SendChannel s30SendChannel;

    public List<String> handle(List<String> destAppIds, String data) throws S30Exception {
        GatewayDataMessage dataMessage = new GatewayDataMessage();
        // 是否需要回应标志位（0表示不需要回应，1表示需要回应）
        dataMessage.getHeader().setRespFlag(s30Config.getProxy().getRespFlag());
        dataMessage.getHeader().setSec(s30Config.getProxy().getSec());
        dataMessage.getHeader().setSrcID(s30Config.getProxy().getAppId());

        List<String> msgIdList = new ArrayList<>();
        destAppIds.stream().forEach(destAppId -> {
            String msgId = StringUtils.EMPTY;
            if ("1".equals(s30Config.getProxy().getRespFlag())) {
                msgId = IdUtil.msgId();
                msgIdList.add(msgId);
            }
            dataMessage.getHeader().addDst(new GatewayDataDest(destAppId, msgId));
        });
        dataMessage.setData(StrUtil.bytes(data, "utf-8"));

        boolean flag = s30SendChannel.asyncSend(dataMessage);
        if (!flag) {
            throw new S30Exception("S30Channel.asyncSend failed");
        }
        return msgIdList;
    }
}
